import logging
import configparser
from pathlib import Path
from logging.handlers import RotatingFileHandler

# --- Get the absolute path to the directory where this script is located ---
SCRIPT_DIR = Path(__file__).resolve().parent
CONFIG_PATH = SCRIPT_DIR / 'config.ini'

def setup_logger():
    """
    Sets up a global, rotating logger based on settings in a config file.
    The config file is assumed to be in the same directory as this script.

    Returns:
        logging.Logger: The configured logger instance.
    """
    config = configparser.ConfigParser()
    # Check if the config file exists
    if not CONFIG_PATH.exists():
        raise FileNotFoundError(f"Configuration file not found at: {CONFIG_PATH}")
    
    config.read(CONFIG_PATH)

    log_dir = Path(config.get('Logging', 'log_directory'))
    log_file = log_dir / config.get('Logging', 'log_filename')
    log_max_bytes = config.getint('Logging', 'log_max_bytes')
    log_backup_count = config.getint('Logging', 'log_backup_count')

    # Ensure the log directory exists
    log_dir.mkdir(exist_ok=True)

    logger = logging.getLogger("VideoProcessingAgent")
    logger.setLevel(logging.INFO)
    
    if not logger.handlers:
        handler = RotatingFileHandler(
            log_file, 
            maxBytes=log_max_bytes, 
            backupCount=log_backup_count,
            encoding='utf-8'
        )
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)

    return logger

# Create a default logger instance for easy import
log = setup_logger()